﻿using System;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using GameViewModel.Annotations;

namespace GameViewModel
{
    public class GameOptions : INotifyPropertyChanged
    {
        public static string FileName = "gamedata.xml";

        private bool _isRandomOrder;

        public GameOptions()
        {
            Unit = 1;
            Persons = new ObservableCollection<Person>();
            Persons.CollectionChanged += PersonsOnCollectionChanged;
        }

        [DisplayName("Стоимость единицы")]
        public int Unit { get; set; }

        public bool IsStartAvailable { get { return Persons.Count(p => p.IsSelected) > 1; } }

        [DisplayName("Рандомизировать порядок игроков")]
        public bool IsRandomOrder
        {
            get { return _isRandomOrder; }
            set
            {
                if (value.Equals(_isRandomOrder)) return;
                _isRandomOrder = value;
                OnPropertyChanged();
            }
        }

        public ObservableCollection<Person> Persons { get; private set; }

        public event PropertyChangedEventHandler PropertyChanged;

        private void PersonsOnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            switch (e.Action)
            {
                case NotifyCollectionChangedAction.Add:
                    foreach (var item in e.NewItems.OfType<Person>())
                        item.PropertyChanged += OnPersonPropertyChanged;
                    break;
                case NotifyCollectionChangedAction.Remove:
                    foreach (var item in e.OldItems.OfType<Person>())
                        item.PropertyChanged -= OnPersonPropertyChanged;
                    break;
                case NotifyCollectionChangedAction.Reset:
                    foreach (var item in Persons)
                        item.PropertyChanged -= OnPersonPropertyChanged;
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }

        private void OnPersonPropertyChanged(object o, PropertyChangedEventArgs args)
        {
            OnPropertyChanged("IsStartAvailable");
        }

        [NotifyPropertyChangedInvocator]
        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            var handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}